<?php

namespace app\admin\controller\calculation;

use app\common\controller\Backend;
use app\admin\model\SalaryCalculationTemplate;
use app\admin\model\SalaryCalculationTemplateItem;
use app\admin\model\Admin;
use app\admin\model\SalaryBenchmark;
use app\admin\model\SalaryItem;
use app\admin\model\SalaryBenchmarkData;
use app\admin\model\SalaryBenchmarkItem;
use app\admin\model\AdminSalaryBenchmarkItem;
use app\admin\model\auth\Asbitemplate;
use app\admin\model\ClassHour;
use app\admin\model\WorkTemplateLog;
use think\Db;
/**
 * 工资管理
 *
 * @icon fa fa-circle-o
 */
class Salary extends Backend
{

    /**
     * Salary模型对象
     * @var \app\admin\model\Salary
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Salary;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['admin'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);


            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {

            $params = $this->request->post('row/a');
            if ($params) {
                set_time_limit(0);
                $params = $this->preExcludeFields($params);
                Db::startTrans();
                try {
                    $salary_culation_template_info = SalaryCalculationTemplate::where('id',$params['template_id'])->find();
                    if(empty($salary_culation_template_info))exception('未找到工资计算模板');

                    $template_item_arr = collection(SalaryCalculationTemplateItem::where('template_id',$params['template_id'])->select())->toArray();
                    if(empty($template_item_arr))exception('未找到工资计算模板计算项目');
//                    $where['ag.group_id'] = 12;//见admin控制器常量
//                    if($salary_culation_template_info['staff_type'] != 1)$where['ag.group_id'] = ['in',array(9,10,11,13,14)];
                    $where['ag.group_id'] = ['not in',array(1,6,8)];
                    $admin_list = (new Admin())->teacher_list($where);

                    $params['admin_id'] = $this->auth->id;
                    $salary_res = $this->model->allowField(true)->save($params);
                    if(empty($salary_res))exception('添加失败');
                    $admin_arr = [];
                    foreach ($admin_list as $value){
//                        $content_arr = [
//                            [
//                                'name'=>"姓名",
//                                'item_type' => 5,
//                                'money'=>$value['name'],
//                            ]
//                        ];
//                        //合计金额
//                        $total_money = 0;
//                        foreach ($template_item_arr as $v){
//                            $money_res = $this->_get_money( $v['formula'],$value['id'],$params['start_time'].'00:00:00',$params['end_time'].'23:59:59');
//                            if($money_res['code'] != 1)exception('计算出错'.$money_res['msg']);
//                            array_push($content_arr,array(
//                                'name' => $v['item_name'],
//                                'item_type' => $v['item_type'],
//                                'money' => $money_res['data']
//                            ));
//                            if($v['item_type'] == 1){
//                                $total_money -= $money_res['data'];
//                            }else{
//                                $total_money += $money_res['data'];
//                            }
////                            if($v['item_type'] == 1){
////                                $total_money -= $money_res['data'];
////                            }elseif($v['item_type'] == 2){
////                                $total_money += $money_res['data'];
////                            }
//                        }
//                        array_push($content_arr,array(
//                            'name'=>"合计",
//                            'item_type' => $total_money > 0 ? 2 : 1,
//                            'money'=>$total_money,
//                        ));
                        array_push($admin_arr,array(
                            'admin_id' => $value['id'],
                            'salary_id' => $this->model->id,
                            'content' => json_encode([]),
                        ));
                    }
                    $salary_item = (new SalaryItem())->saveAll($admin_arr);
                    if(empty($salary_item))exception('添加失败');
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $ids = explode(',',$ids);
            Db::startTrans();
            try {
                $this->model->whereIn('id',$ids )->delete();
                (new SalaryItem())->whereIn('salary_id',$ids )->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 导出数据
     */
    public function export($ids = "")
    {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        set_time_limit(0);
        $excel = new \PHPExcel();

        // 添加工作表
        $excel->setActiveSheetIndex(0);
        $sheet = $excel->getActiveSheet();
        $salary_list = collection(SalaryItem::with('admin')->where(['salary_id'=>$row->id])->select())->toArray();

        $headers = [];
        if($salary_list){
            $content = json_decode($salary_list[0]['content'],true);
            foreach ($content as $contentItem) {
                $headers[] = $contentItem['name'];
            }
        }

        $centerStyle = new \PHPExcel_Style();
        $centerStyle->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);


        $columnIndex = 0;
        foreach ($headers as $header) {
            $cell = $sheet->setCellValueByColumnAndRow($columnIndex, 1, $header);
            // 获取单元格坐标
            $cellCoordinate = \PHPExcel_Cell::stringFromColumnIndex($columnIndex) . '1';
            // 获取现有样式
            $existingStyle = $sheet->getStyle($cellCoordinate);
            // 合并样式
            $existingStyle->applyFromArray([
                'alignment' => [
                    'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                ],
            ]);
            // 设置单元格宽度
            $sheet->getColumnDimensionByColumn($columnIndex)->setWidth(20); // 根据需要调整宽度因子
            $columnIndex++;
        }

        $rowIndex = 2;
        foreach ($salary_list as $item) {
            $content = json_decode($item['content'], true);
            $columnIndex = 0;

            foreach ($content as $c) {
//                if ($c['item_type'] === 4 || $c['item_type'] === 3 || $c['item_type'] === 2) {
//                    $cellValue = $c['money'];
//                } elseif ($c['item_type'] === 1) {
//                    $cellValue = '-' . $c['money'];
//                }
                $cell = $sheet->setCellValueByColumnAndRow($columnIndex, $rowIndex, $c['money']);
                // 获取单元格坐标
                $cellCoordinate = \PHPExcel_Cell::stringFromColumnIndex($columnIndex) . $rowIndex;
                // 获取现有样式
                $existingStyle = $sheet->getStyle($cellCoordinate);
                // 合并样式
                $existingStyle->applyFromArray([
                    'alignment' => [
                        'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                    ],
                ]);

                $columnIndex++;
            }
            $rowIndex++;
        }

        $excel->createSheet();
        $title = $row['name']. date("YmdHis");
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');

        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
        return;
    }

    public function _get_money($formula,$admin_id,$start_time,$end_time)
    {
        try{
            $formula = json_decode($formula,true);
            $new_formula = '';
            foreach ($formula as $item) {
                if ($item['type'] == '2' || $item['type'] == '3') { // 2 计算公式 3 自定义数值
                    $new_formula .= $item['value'];
                } elseif ($item['type'] == '1') {  // 1:选择的计算项
                    $value_arr = explode('-',$item['value']);
                    if(empty($value_arr))exception('计算公式格式错误');
                    if($value_arr[0] == 999){ // 新加内容
                        switch ($value_arr[1]) {
                            case 1:  // 值白班
                                $single_price = $this->single_price(3);
                                // 计算次数
                                $number = calculate_count(1,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            case 2:  // 值夜班
                                $single_price = $this->single_price(4);
                                // 计算次数
                                $number = calculate_count(2,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            case 3:  // 值夜宿班
                                $single_price = $this->single_price(5);
                                // 计算次数
                                $number = calculate_count(3,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            case 4:  // 社团费用
                                $z_single_price = $this->single_price(16);
                                // 计算次数
                                $z_number = calculate_count(8,$admin_id,$start_time,$end_time);

                                $h_single_price = $this->single_price(17);
                                // 计算次数
                                $h_number = calculate_count(9,$admin_id,$start_time,$end_time);
                                $value = $z_single_price * $z_number + $h_single_price * $h_number;
                                break;
                            case 5:  // 课业辅导费用
                                $single_price = $this->single_price(7);
                                // 计算次数
                                $number = calculate_count(5,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            case 6:  // 护导费用
                                $single_price = $this->single_price(8);
                                // 计算次数
                                $number = calculate_count(6,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            case 7:  // 代班主任费用
                                $single_price = $this->single_price(9);
                                $number = simple_count(7,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            case 8:  // 被代班主任费用
                                $single_price = $this->single_price(10);
                                $number = simple_count(8,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            case 11:  // 主科-课时费用
                                $single_price = $this->single_price(12);
                                $number = subject_calculate(11,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            case 12:  // 主科-代课费用
                                $single_price = $this->single_price(10);
                                $number = subject_calculate(12,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            case 13:  // 主科-被代课费用
                                $single_price = $this->single_price(10);
                                $number = subject_calculate(13,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            case 14:  // 科任-课时费用
                                $single_price = $this->single_price(12);
                                $number = subject_calculate(14,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            case 15:  // 科任-代课费用
                                $single_price = $this->single_price(10);
                                $number = subject_calculate(15,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            case 16:  // 科任-被代课费用
                                $single_price = $this->single_price(10);
                                $number = subject_calculate(16,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            case 17:  // 班队会-课时费用
                                $single_price = $this->single_price(12);
                                $number = subject_calculate(17,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            case 18:  // 班队会-代课费用
                                $single_price = $this->single_price(10);
                                $number = subject_calculate(18,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            case 19:  // 班队会-被代课费用
                                $single_price = $this->single_price(10);
                                $number = subject_calculate(19,$admin_id,$start_time,$end_time);
                                $value = $single_price * $number;
                                break;
                            default:
                                $value = 0;
                                break;
                        }

                    }else{
                        switch ($value_arr[1]){
                            case 1:  // 计算项
                                $salary_benchmark_info = SalaryBenchmark::where('id',$value_arr[0])->find();
                                if(empty($salary_benchmark_info))exception('自定义基准项未找到');
                                if($salary_benchmark_info['count_type'] == 1){ // 次数
                                    $num = SalaryBenchmarkData::where([
                                        'status'=>4,
                                        'salary_benchmark_id'=>$salary_benchmark_info['id'],
                                        'admin_id'=>$admin_id
                                    ])
                                        ->whereTime('select_time', 'between', [$start_time, $end_time])
                                        ->sum('num');
                                    $value = $salary_benchmark_info['num_price']*$num;
                                }else{
                                    $value = AdminSalaryBenchmarkItem::with('item')
                                        ->where(['admin_salary_benchmark_item.salary_benchmark_id'=>$salary_benchmark_info['id'],'admin_id'=>$admin_id])
                                        ->sum('item.price');
                                    if(!$value){
                                        // 查分组
                                        $group_ids = Db::table('b_admin_group_access')->where('uid',$admin_id)->column('group_id');
                                        $asbi_template_arr =  Db::table('b_admin_group_asbi')->whereIn('group_id',$group_ids)->column('asbi_template_id');;
                                        $value = Db::table('b_auth_asbi_template_item a')
                                            ->join('salary_benchmark_item b','a.salary_benchmark_item_id=b.id')
                                            ->whereIn('template_id',$asbi_template_arr)
                                            ->where('a.salary_benchmark_id',$salary_benchmark_info['id'])
                                            ->sum('b.price');
                                    }
                                }
                                break;
                            case 2:  // 日常课程
                                $value = ClassHour::where(['type'=>1,'status'=>5,'admin_id'=>$admin_id,'course_type_id'=>$value_arr[0]])
                                    ->whereTime('select_time', 'between', [$start_time, $end_time])
                                    ->sum('num');
                                break;
                            case 3:  // //代课
                                $value = ClassHour::where(['type'=>2,'status'=>5,'substitute_admin_id'=>$admin_id,'course_type_id'=>$value_arr[0]])
                                    ->whereTime('select_time', 'between', [$start_time, $end_time])
                                    ->sum('num');
                                break;
                            case 4:  // 浮动性工资
                                $where = [];
                                if($value_arr[0] == 3)$where['teacher_type'] = 1;
                                $value = WorkTemplateLog::where(['type'=>$value_arr[0],'status'=>5,'admin_id'=>$admin_id])->where($where)
                                    ->whereTime('select_time', 'between', [$start_time, $end_time])
                                    ->count();
                                if($value_arr[0] == 1){ // 1 分餐
                                    $single_price = $this->single_price(1);
                                }else if($value_arr[0] == 2){ // 看班
                                    $single_price = $this->single_price(2);
                                }else { // 看班
                                    $single_price = 0;
                                }
                                $value = $value * $single_price;
                                break;
                            case 5:  // 浮动性工资助教
                                $value = WorkTemplateLog::where(['type'=>$value_arr[0],'status'=>5,'admin_id'=>$admin_id,'teacher_type'=>2])
                                    ->whereTime('select_time', 'between', [$start_time, $end_time])
                                    ->count();
                                break;
                            default:
                                $value = 0;
                                break;
                        }
                    }
                    $new_formula .= $value;

                }
            }
            $money = 0;
            eval('$money = ' . $new_formula . ';');
            return array('code'=>1,'msg'=>'ok','data'=>$money);
        }catch (\Throwable $e){
            return array('code'=>0,'msg'=>$e->getMessage());
        }

    }


    // 计算单次价格
    public function single_price($id){
        return Db::table('b_basis_cost')->where('id',$id)->value('price');
    }



}
